package com.gyz.taxiplus;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.search.MKRoute;
import com.baidu.platform.comapi.basestruct.GeoPoint;

import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;

public class FeeActivity extends Activity {

	private BMapManager mapmanager;
	private MapView mapview;
	private MapController mapcontroller;
	private LocationClient locationclient;
	private FeeLocationListener locationlistener = new FeeLocationListener();
	private List<GeoPoint> points = new ArrayList<GeoPoint>();
	private RouteOverlay routeoverlay;
	private MKRoute route = new MKRoute();
	private long waittime = 0;
	private double distance = 0;
	private Date lastwait;
	private TextView summary;
	private Date starttime;
	private GeoPoint[] pointarray = new GeoPoint[100];
	private boolean lostgps = true;
	private int currentfee = 0;
	private String city;
	private Pay pay;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		mapmanager = new BMapManager(getApplication());
		mapmanager.init("6EC2C3605D628B25C945B9D56F2F9F4EE7C463A7", null);
		setContentView(R.layout.activity_fee);
		locationclient = new LocationClient(getApplicationContext());
		locationclient.registerLocationListener(locationlistener);
		setOption();
		summary = (TextView) findViewById(R.id.summary);
		mapview = (MapView) findViewById(R.id.mapview);
		mapview.setBuiltInZoomControls(true);
		mapview.setTraffic(true);
		mapcontroller = mapview.getController();
		locationclient.start();
		locationclient.requestLocation();
		mapcontroller.setZoom(17);
		routeoverlay = new RouteOverlay(this, mapview);
		mapview.getOverlays().add(routeoverlay);
		Toast.makeText(getApplicationContext(), R.string.searchgpsLabel,
				Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onPause() {
		mapview.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mapview.onResume();
		super.onResume();
	}

	@Override
	protected void onStop() {
		locationclient.stop();
		mapview.destroy();
		super.onStop();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		mapview.onSaveInstanceState(outState);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		mapview.onRestoreInstanceState(savedInstanceState);
		super.onRestoreInstanceState(savedInstanceState);
	}

	private void setOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");
		option.setCoorType("bd09ll");
		option.setServiceName("com.baidu.location.service_v3.3");
		option.setPoiExtraInfo(false);
		option.disableCache(true);
		option.setScanSpan(3 * LocationClientOption.MIN_SCAN_SPAN);
		option.setPriority(LocationClientOption.GpsFirst);
		locationclient.setLocOption(option);
	}

	private class FeeLocationListener implements BDLocationListener {

		@SuppressWarnings("deprecation")
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (city != null) {
				if (location.getLocType() == 61) {
					GeoPoint current = new GeoPoint(
							WelcomeActivity.geoTransfer(location.getLatitude()),
							WelcomeActivity
									.geoTransfer(location.getLongitude()));
					mapcontroller.animateTo(current);
					points.add(current);
					int sn = location.getSatelliteNumber();
					if (sn > 0) {
						if (points.size() == 1) {
							starttime = new Date();
							int hour = starttime.getHours();
							if (hour < 5 || hour >= 23) {
								pay = Pay.getNightPay(city);
							} else {
								pay = Pay.getDayPay(city);
							}
						} else {
							route.customizeRoute(points.get(0),
									points.get(points.size() - 1),
									(GeoPoint[]) points.toArray(pointarray));
							distance = route.getDistance();
						}
						if (null == lastwait) {
							if (location.getSpeed() < 12) {
								lastwait = new Date();
							}
						} else {
							Date now = new Date();
							waittime += (now.getHours() - lastwait.getHours())
									* 3600
									+ (now.getMinutes() - lastwait.getMinutes())
									* 60 + now.getSeconds()
									- lastwait.getSeconds();
							if (location.getSpeed() < 12) {
								lastwait = now;
							} else {
								lastwait = null;
							}
						}
						routeoverlay.setData(route);
						mapview.refresh();
					} else if (null != lastwait) {
						Date now = new Date();
						waittime += (now.getHours() - lastwait.getHours())
								* 3600
								+ (now.getMinutes() - lastwait.getMinutes())
								* 60 + now.getSeconds() - lastwait.getSeconds();
						lastwait = now;
					}
					if (lostgps) {
						lostgps = false;
					}
					summary.setText(getSummeryContent(
							(int) location.getSpeed(), sn, true));
					return;
				}
				if (location.getLocType() == 161) {
					GeoPoint current = new GeoPoint(
							WelcomeActivity.geoTransfer(location.getLatitude()),
							WelcomeActivity
									.geoTransfer(location.getLongitude()));
					mapcontroller.animateTo(current);
				}
				if (null != lastwait) {
					Date now = new Date();
					waittime += (now.getHours() - lastwait.getHours()) * 3600
							+ (now.getMinutes() - lastwait.getMinutes()) * 60
							+ now.getSeconds() - lastwait.getSeconds();
					lastwait = now;
				}
				summary.setText(getSummeryContent(0, -1, false));
				if (!lostgps) {
					Toast.makeText(getApplicationContext(),
							R.string.lostgpsLabel, Toast.LENGTH_SHORT).show();
					lostgps = true;
				}
			} else if (location.getLocType() == 161) {
				GeoPoint current = new GeoPoint(
						WelcomeActivity.geoTransfer(location.getLatitude()),
						WelcomeActivity.geoTransfer(location.getLongitude()));
				mapcontroller.animateTo(current);
				if (null == city) {
					city = location.getCity();
					Toast.makeText(getApplicationContext(), city,
							Toast.LENGTH_SHORT).show();
				}
			}
		}

		@Override
		public void onReceivePoi(BDLocation poi) {
		}

	}

	public String getSummeryContent(int speed, int satelliteNumber,
			boolean calcfee) {
		StringBuilder sb = new StringBuilder();
		sb.append(getString(R.string.distanceLabel));
		sb.append(distance / 1000);
		sb.append("km\t");
		sb.append(getString(R.string.waitLabel));
		int waithour = (int) (waittime / 3600);
		int waitminute = (int) ((waittime - waithour * 3600) / 60), waitsecond = (int) (waittime % 60);
		sb.append(waithour);
		sb.append(':');
		if (waitminute < 10) {
			sb.append('0');
		}
		sb.append(waitminute);
		sb.append(':');
		if (waitsecond < 10) {
			sb.append('0');
		}
		sb.append(waitsecond);
		sb.append('\n');
		sb.append(getString(R.string.velocityLabel));
		sb.append(speed);
		sb.append("km/h\t");
		sb.append(getString(R.string.moneyLabel));
		if (calcfee) {
			currentfee = pay.calculate(distance, waittime);
		}
		sb.append(currentfee);
		sb.append(".00\nSatellite:");
		sb.append(satelliteNumber);
		return sb.toString();
	}

}